/**
 * 
 */
package unseen.labs.games.mysnake.view.renderer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import unseen.labs.games.mysnake.model.Ball;
import unseen.labs.games.mysnake.model.Racket;

import android.opengl.GLSurfaceView;
import android.view.MotionEvent;

/**
 * @author PERRAUDIN Steven <sperraudin@neotilus.com>
 *
 * @date 4 juin 2010
 */
public class GenericRenderer implements GLSurfaceView.Renderer{

	private float _red 	= 0f;
    private float _green 	= 0f;
    private float _blue 	= 0f;
	
    private float _angle;
    
    private float _width 	= 320f;
    private float _height 	= 480f;
    
    private Racket _rRacket;
    private Ball _rBall;
        
    public boolean _ingame = false;
    
	public GenericRenderer(){
		
	}
	
	@Override
	public void onDrawFrame(GL10 gl) {
		
		if(_ingame){
			moveBall();
		}
		
		// define the color we want to be displayed as the "clipping wall"
        gl.glClearColor(_red, _green, _blue, 1.0f);
        
        // reset the matrix - good to fix the rotation to a static angle
        gl.glLoadIdentity();
        
        // clear the color buffer to show the ClearColor we called above...
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
        
        // set rotation
        gl.glRotatef(_angle, 0f, 1f, 0f);
        
        gl.glColor4f(0.5f, 0f, 0f, 0.5f);
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, _rRacket.getVertexBuffer());
        gl.glDrawElements(GL10.GL_TRIANGLES, _rRacket.getNrOfVertices(), GL10.GL_UNSIGNED_SHORT, _rRacket.getIndexBuffer());
		
        gl.glColor4f(0f, 0.5f, 0f, 0.5f);
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, _rBall.getVertexBuffer());
        gl.glDrawElements(GL10.GL_TRIANGLE_FAN, _rBall.getNrOfVertices(), GL10.GL_UNSIGNED_SHORT, _rBall.getIndexBuffer());
		
	}

	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		System.out.println("onSurfaceChanged");
		gl.glViewport(0, 0, width, height);
	}

	@Override
	public void onSurfaceCreated(GL10 gl, EGLConfig config) {
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);		
		_rRacket 	= new Racket();
		_rBall 		= new Ball();
		
		_ingame 	= true;
	}

	private void moveBall() {
				
		if(_rBall.tagada(_rRacket)){;
			_rBall.move();
		}
		else{
			_ingame = false;
		}
	}
	
	public void restartGame(){
		_rBall 		= new Ball();		
		_ingame 	= true;
	}

	public void setRacketPosition(float oldX, float x) {
		
		if(oldX > x){		// move right
			_rRacket.moveLeft();
		}
		else if(oldX < x){	// move left
			_rRacket.moveRight();
		}
		
	}
}
